package com.wolffy.flink.split;

import com.wolffy.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class SideOutputDemo {
    public static void main(String[] args) throws Exception {

        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 7777);

        //手动数据数据   s1,1,2
        SingleOutputStreamOperator<WaterSensor> sensorDS = env.socketTextStream("hadoop102", 6666)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        // TODO 使用侧输出流 实现分流

        //         *    1、使用 process算子
        //         *    2、定义 OutputTag对象
        //         *    3、调用 ctx.output
        //         *    4、通过主流 获取 测流

        // 创建OutputTag对象 第一个参数： 标签名 第二个参数： 放入侧输出流中的 数据的 类型，Typeinformation
        OutputTag<WaterSensor> s1Tag = new OutputTag<>("s1", Types.POJO(WaterSensor.class));
        OutputTag<WaterSensor> s2Tag = new OutputTag<>("s2", Types.POJO(WaterSensor.class));

        SingleOutputStreamOperator<WaterSensor> process = sensorDS
                .process(new ProcessFunction<WaterSensor, WaterSensor>() {
                             @Override
                             public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {
                                 if ("s1".equals(value.getId())) {
                                     ctx.output(s1Tag, value);
                                 } else if ("s2".equals(value.getId())) {
                                     ctx.output(s2Tag, value);
                                 } else {
                                     out.collect(value);
                                 }
                             }
                         }
                );
        // 从主流中，根据标签 获取 侧输出流
        SideOutputDataStream<WaterSensor> s1 = process.getSideOutput(s1Tag);
        SideOutputDataStream<WaterSensor> s2 = process.getSideOutput(s2Tag);

        // 打印主流
        process.print("主流-非s1、s2");

        //打印 侧输出流
        s1.printToErr("s1");
        s2.printToErr("s2");

        env.execute();
    }
}

